#include "playlistwidget.h"
#include "ui_playlistwidget.h"
#include "songmanager.h"

#include <QPainter>
PlaylistWidget::PlaylistWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PlaylistWidget)
{
    ui->setupUi(this);
    QVBoxLayout *containerLayout = static_cast<QVBoxLayout*>(ui->container->layout());
    containerLayout->setAlignment(Qt::AlignTop);       // 布局内所有子控件顶对齐
    containerLayout->setContentsMargins(60, 0, 57, 0);    // 左边距60, 右边距 60-3

    // ban掉可能出现的横向滑动条
    ui->scrollArea->setWidgetResizable(true);
    ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 永久关掉横向
    ui->scrollArea->viewport()->installEventFilter(this); // 添加事件过滤器来处理滚动区域大小变化
    setListImage(":/image/ui/logo.png");
}

#include <QResizeEvent>
// 添加事件过滤器函数以处理大小变化
bool PlaylistWidget::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->scrollArea->viewport() && event->type() == QEvent::Resize) {
        // 当窗口大小变化时调整container的最小宽度
        QResizeEvent *resizeEvent = (QResizeEvent*)(event);
        int newWidth = resizeEvent->size().width();
        ui->container->setMinimumWidth(newWidth);
    }

    return QWidget::eventFilter(watched, event);
}

void PlaylistWidget::setListId(int listId)
{
    _listId = listId;
    auto list = SongManager::instance()->getSongList(listId);
    for(int i = list.size() - 1; i >= 0; i--){
        const SongItem& item = SongManager::instance()->getSongItem(list[i]);
        SongItemWidget* songItemWidget = new SongItemWidget(this);
        songItemWidget->setSongItem(item);
        addSongItem(songItemWidget);
    }
}

PlaylistWidget::~PlaylistWidget()
{
    delete ui;
}

#include <QDebug>
void PlaylistWidget::addSongItem(SongItemWidget *songItem)
{
    _songItems.push_front(songItem);
    connect(songItem, &SongItemWidget::played, this, &PlaylistWidget::on_songItem_played);
    connect(songItem, &SongItemWidget::downloaded, this, &PlaylistWidget::on_songItem_downloaded);
//    ui->container->layout()->addWidget(songItem);
    static_cast<QVBoxLayout*>(ui->container->layout())->insertWidget(1, songItem);
    setListImage(songItem->songItem().image);
    updateindex();
    songItem->connectManager();
}

void PlaylistWidget::setListImage(const QString &path)
{
    QPixmap pixmap(path);
    pixmap = pixmap.scaled(ui->label_listImage->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->label_listImage->setPixmap(QPixmap(path));
}

void PlaylistWidget::setListImage(const QPixmap &pixmap)
{
    QPixmap Spixmap= pixmap.scaled(ui->label_listImage->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QPixmap roundedPixmap(ui->label_listImage->size());
    roundedPixmap.fill(Qt::transparent);

    QPainter painter(&roundedPixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    painter.setBrush(QBrush(Spixmap));
    painter.drawRoundedRect(Spixmap.rect(), 15, 15);

    ui->label_listImage->setPixmap(roundedPixmap);
}

void PlaylistWidget::on_SongManager_liked(QUrl url, bool isLike)
{
    if (isLike){
       const SongItem& item = SongManager::instance()->getSongItem(url);
       SongItemWidget* songItemWidget = new SongItemWidget(this);
       songItemWidget->setSongItem(item);
       addSongItem(songItemWidget);
    } else {
        for(int i = 0; i < _songItems.size(); i++){
            if (_songItems[i]->songItem().url() == url){
                disconnect(_songItems[i], &SongItemWidget::played, this, &PlaylistWidget::on_songItem_played);
                _songItems[i]->deleteLater();
                _songItems.removeAt(i);
            }
        }
        updateindex();
        if(_songItems.size()) setListImage(_songItems.front()->songItem().image);
    }
}

void PlaylistWidget::on_songItem_played(int index, bool play)
{
    emit played(_songItems[index]->songItem(), play);
}

void PlaylistWidget::on_songItem_downloaded()
{
    storage();
}

void PlaylistWidget::updateindex()
{
    int i = 1;
    for(auto& e : _songItems) e->setIndex(i++);
    storage();
}

void PlaylistWidget::storage()
{
    QList<QUrl> list;
    for(auto& e : _songItems){
        list.push_back(e->songItem().url());
    }
    SongManager::instance()->updateSongList(_listId, list);
}

#include <QTimer>
void PlaylistWidget::on_pushButton_playAll_clicked()
{
    QVector<QUrl> songs;
    for(auto& e : _songItems){
        songs.push_back(e->songItem().url());
    }
    emit playAll(songs);
}

void PlaylistWidget::on_pushButton_utils_clicked()
{

}

#include <QNetworkAccessManager>
#include <QNetworkReply>
void PlaylistWidget::downloadSong(qint64 id, const QString& path)
{
    qDebug() << "准备下载歌曲: " << path;
    static QNetworkAccessManager* _manager = new QNetworkAccessManager(this);
    QString urlStr = "http://music.163.com/song/media/outer/url?id=" + QString::number(id) + ".mp3";
    QNetworkRequest request;
    request.setUrl(QUrl(urlStr));
    QNetworkReply* reply = _manager->get(request);
    connect(reply, &QNetworkReply::finished, this, [=](){
        if(reply->error() != QNetworkReply::NoError){
            qDebug() << "请求出错: " << reply->errorString();
            reply->deleteLater();
            return;
        }
        QUrl songUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
        if(!songUrl.isEmpty() && songUrl != QUrl("http://music.163.com/404")){
            QNetworkRequest request;
            request.setUrl(QUrl(songUrl));
            QNetworkReply* reply2 = _manager->get(request);
            connect(reply2, &QNetworkReply::finished, this, [=](){
                if(reply2->error() != QNetworkReply::NoError){
                    qDebug() << "请求出错: " << reply2->errorString();
                    reply2->deleteLater();
                    return;
                }
                QByteArray data = reply2->readAll();
                QFile file(path);
                if (!file.open(QIODevice::WriteOnly)) {
                    qDebug() << "文件打开失败：" << file.errorString();
                    return;
                }
                file.write(data);
                file.close();
                SongManager::instance()->download(id);
                reply2->deleteLater();
            });
        }
        reply->deleteLater();
    });
}


#include <QDir>
void PlaylistWidget::on_pushButton_download_clicked()
{
    qDebug() << "下载按钮被点击";
    for(auto& e : _songItems){
        if(e->songItem().local_url.isEmpty()){
            QString path = e->songItem().name + " - " + e->songItem().artist + ".mp3";
            for(auto c : {'<', '>', ':', '"', '/', '\\', '|', '?', '*'})
                path.replace(c, ',');
            path = "cloudMusic/" + path;
            qDebug() << path;
            if(!QDir().exists(path)){
                downloadSong(e->songItem().wangyiyun_id, path);
            }
        }
    }
}
